<template>
  <div class="app-container">
    <el-form :model="queryParams" :rules="rules" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px"
             onsubmit="return false;">
      <el-form-item label="模板名称" prop="condition[name|like]">
        <el-input
          v-model="queryParams['condition[name|like]']"
          placeholder="请输入模板名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:type:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="模板名称" align="center" prop="icons">
        <template slot-scope="scope">
          <img class="row-icons" :src="scope.row.icons"/>
          <div class="row-label"> {{ scope.row.name }}</div>
        </template>
      </el-table-column>
      <el-table-column label="模板类型" align="center" prop="templateType">
        <template slot-scope="scope">
          <span v-if="scope.row.templateType == 'maven'">
            <i class="fab fa-java font-icons"></i> Maven
          </span>
        </template>
      </el-table-column>
      <el-table-column label="业务类型" align="center" prop="businessType">
        <template slot-scope="scope">
          {{ businessConvert(scope.row.businessType) }}
        </template>
      </el-table-column>
      <el-table-column label="查看模板" align="center" prop="templateType">
        <template slot-scope="scope">

          <el-button
            type="text"
            v-if="scope.row.mavenXml"
            icon="el-icon-s-claim"
            @click="showTemplate(scope.row)"
          >查看模板
          </el-button>

          <el-button
            v-if="!scope.row.mavenXml"
            type="text"
            style="color:red"
            icon="el-icon-top"
            @click="handleUpdate(scope.row)"
          >上传模板
          </el-button>

        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模板类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="模板类型" prop="templateType">
          <el-radio-group v-model="form.templateType">
            <el-radio label="maven">maven</el-radio>
            <el-radio label="npm">npm</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.icons != 'F'" label="模板图标">
          <img class="gvwTmF" @click="projectIconsVisible = true" :src="projectIconSelect"/>
        </el-form-item>

        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称"/>
        </el-form-item>
        <el-form-item label="模板说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入模板说明"/>
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-radio-group v-model="form.businessType">
            <el-radio label="mobile">移动端</el-radio>
            <el-radio label="manager">管理端</el-radio>
            <el-radio label="component">组件端</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模板内容" prop="mavenXml">
          <!--
          <el-input v-model="form.mavenXml" rows="8" type="textarea" placeholder="请输入MavenXml模板说明" />
          -->
          <el-upload
            class="upload-demo"
            :action="uploadPath"
            :headers="myHeaders"
            :on-change="handleChange"
            :on-success="handleUploadSuccess"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传yaml格式文件，且不超过60kb</div>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择项目图标"
      :visible.sync="projectIconsVisible"
      width="600px">

      <el-avatar :size="50" class="projectIcon" :key="index" v-for="(item , index) in 26" src="https://empty">
        <img :src="showProjectIcon(item)" @click="selectProjectIcons(item)"/>
      </el-avatar>

      <span slot="footer" class="dialog-footer">
                <el-button @click="projectIconsVisible = false">取 消</el-button>
            </span>
    </el-dialog>

    <!-- 显示模板信息 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogTemplateVisible"
      width="700px">

      <json-viewer
        :value="jsonData"
        :expand-depth="5"
        copyable
        sort></json-viewer>

      <span slot="footer" class="dialog-footer">
            <el-button @click="dialogTemplateVisible = false">关  闭</el-button>
          </span>
    </el-dialog>

  </div>
</template>

<script>

  import {DictSelect, IconSelect} from "alinesno-ui";
  import JsonViewer from "vue-json-viewer";

  import {
    addBuildApplicationTemplate,
    delBuildApplicationTemplate,
    getBuildApplicationTemplate,
    listBuildApplicationTemplate,
    updateBuildApplicationTemplate,
    uploadTemplate
  } from "./api";

  var token = "Bearer " + localStorage.getItem('access_token');

  export default {
    name: "Type",
    components: {
      DictSelect,
      IconSelect,
      JsonViewer,
    },
    data() {
      return {
        projectIconsVisible: false,
        projectIconSelect: 'https://gw.alicdn.com/tfs/TB197e_CHrpK1RjSZTEXXcWAVXa-102-102.png',
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        uploadPath: '',
        // 文件列表
        fileList: [],
        jsonData: null,
        myHeaders: {Authorization: token},
        // 非单个禁用
        single: true,
        dialogTemplateVisible: false,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 模板类型表格数据
        typeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          'condition[name|like]': null,
          dictType: null,
          status: null,
        },
        // 表单参数
        form: {
          icons: '',
          templateType: 'maven',
          businessType: 'manager',
          mavenXml: '',
        },
        // 表单校验
        rules: {
          remark: {required: true, message: "请输入模板说明", trigger: "blur"},
          name: {required: true, message: "请输入模板名称", trigger: "blur"},
          icons: {required: true, message: "请选择图标", trigger: "blur"},
          templateType: {required: true, message: "请选择模板类型", trigger: "blur"},
          businessType: {required: true, message: "请选择业务类型", trigger: "blur"},
          mavenXml: {required: true, message: "请选择模板内容", trigger: "blur"}
        }
      };
    },
    created() {
      this.getList();
      var rPath = uploadTemplate();
      console.log('rPath = ' + rPath);
      this.uploadPath = rPath;
    },
    methods: {
      handleUploadSuccess(response, file, fileList) {
        this.form.mavenXml = response.data;
      },
      handleChange(file, fileList) {
        this.fileList = fileList.slice(-1);
      },
      selectProjectIcons(item) {
        this.projectIconsVisible = false;
        this.projectIconSelect = require('@/asserts/icons/component/component_' + item + '.png')
      },
      showTemplate(item) {
        console.log('item = ' + item);
        this.dialogTemplateVisible = true;
        this.jsonData = JSON.parse(item.mavenXml);
      },
      templateConvert(v) {
        if ('maven' === v) {
          return '<i class="fab fa-java"></i>Maven';
        } else if ('npm' === v) {
          return '组件端';
        }
        return v;
      },
      businessConvert(v) {
        if ('manager' === v) {
          return '管理端';
        } else if ('component' === v) {
          return '组件端';
        } else if ('mobile' === v) {
          return '移动端';
        }
        return v;
      },
      showProjectIcon(item) {
        return require('@/asserts/icons/component/component_' + item + '.png');
      },
      /** 查询模板类型列表 */
      getList() {
        this.loading = true;
        listBuildApplicationTemplate(this.queryParams).then(response => {
          this.typeList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 选择图标
      selected(name) {
        this.form.icon = name;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          dictName: null,
          dictType: null,
          status: "0",
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加模板类型";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getBuildApplicationTemplate(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改模板类型";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          this.form.icons = this.projectIconSelect;
          if (valid) {
            if (this.form.id != null) {
              updateBuildApplicationTemplate(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.fileList = [];
              });
            } else {
              addBuildApplicationTemplate(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.fileList = [];
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除模板类型编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delBuildApplicationTemplate(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有模板类型数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportBuildApplicationTemplate(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
      }
    }
  };
</script>

<style scoped lang="scss">
  .projectIcon {
    margin: 10px;
    cursor: pointer;
    background: #f7f9fa;
  }

  .gvwTmF {
    display: flex;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    cursor: pointer;
    align-items: center;
    margin-bottom: 0px;
    background-size: 100%;
    background-color: transparent;
  }

  .row-label {
    float: left;
    line-height: 35px;
    margin-left: 10px;
  }

  .row-icons {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    float: left;
  }

  .font-icons {
    font-size: 20px;
    color: #005BD4;
  }

</style>
